<?php

/**
 * 函数库
 * author: 爱是西瓜
 * DateTime: 2018/5/01
 */


/**
 * 调试输出
 * @param $msg
 */
function dump($msg){
    if(is_array($msg)){
        $msg = json_encode($msg);
    }
    echo $msg."\n";
}


/**
 * 组装返回数据
 * @author:爱是西瓜
 * @param $type 信息类别
 * @param $data 返回数据
 * @param int $code 返回状态码
 * @param string $msg 返回状态信息
 * @return string 转换的json数据
 */
function myResult($type,$data,$code=200,$msg='请求成功'){
    $result = [
        'code'=>$code,
        'msg'=>$msg,
        'message_type'=>$type,
        'data'=>$data
    ];
    return json_encode($result);
}

/**
 * 获取GET请求
 * @param $url
 * @param array $params
 * @param int $timeout
 */
function curl_get($url, array $params = array(), $timeout = 5)
{
    if($params){
        $attr = strpos($url,'?')?'&':'?';
        foreach ($params as $k=>$v){
            $attr .= $k.'='.$v;
        }
        $url .= $attr;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;
}

/**
 * 获取POST请求
 * @param $url
 * @param array $params
 * @param $timeout
 * @return mixed
 */
function curl_post($url, array $params = array(), $timeout){
    $ch = curl_init();//初始化
    curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return ($data);
}